package com.lvwenguo.user.controller;


import com.lvwenguo.returnresult.Result;
import com.lvwenguo.token.JwtUtil;
import com.lvwenguo.user.entity.User;
import com.lvwenguo.user.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.jms.Topic;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private Result result;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("/test")
    public List<User> test() {
        return userService.selectUser();
    }



    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;
    /**
     * MQ
     * @param mq
     * @return
     */
    @GetMapping("/mq")
    public String mq(@Param("mq") String mq) {
        jmsMessagingTemplate.convertAndSend(topic, mq);
        return mq;
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @GetMapping("/login")
    public Result<String> login(@Param("user") User user) {
        if(user.getUserName()==null || user.getUserName().equals("")){
            return result.error("登录失败");
        }
        //根据用户名查询数据库
        User user1 = userService.login(user.getUserName(),user.getUserPassword());
        //判断用户是否存在
        if (ObjectUtils.isEmpty(user1)) {
            return result.error("登录失败");//返回null，默认是UnknownAccountException异常
        } else {
            //到达这里表示数据库存在用户信息,一个小时后过期
            String token = jwtUtil.encode(user.getUserName(), (3600*1000), new HashMap<>());
            Map<String,String> map=new HashMap<>();
            map.put("Authorization",token);
            return result.ok(map);
        }
    }

    @PostMapping("/saveUser")
    public Result<Map<Integer,String>> saveUser(User user){
        return result.ok(this.userService.saveUser(user));
    }

}
